/**
 * Created by ZHOUSH on 12/4/2015.
 */
var fs = require('fs');
var Promise = require('promise');
var xml2js = require('xml2js');
var pparseXml = Promise.denodeify(xml2js.parseString);
var pread = Promise.denodeify(fs.readFile);
var pwrite = Promise.denodeify(fs.writeFile);

var xml_path = '\\rdfxml';
var parse = function (name) {
    return pread(__dirname + xml_path + '\\' + name + '.xml', 'utf-8').then(function (data) {
        return pparseXml(data);
    })
};
var fetchSql = function (name) {
    return parse(name).then(function (data) {
        return data.report.data.reduce(function (pre, item) {
            pre = pre.concat(item.dataSource);
            return pre;
        }, []).reduce(function (pre, ds) {
            if (!ds.select) {
                return pre;
            }
            pre = pre.concat(ds.select.map(function (select) {
                if (typeof select == 'string') {
                    return select;
                } else if (typeof select == 'object' && '_' in select) {
                    return select['_'];
                }
                return select;
            }));
            return pre;
        }, []);
    })
};
var fetchFormular = function (name) {
    return parse(name).then(function (data) {
        if ('programUnit' in data['report']) {
            return data['report']['programUnits'].reduce(function (pre, item) {
                pre = pre.concat(item['function']);
                return pre;
            }, []).reduce(function (pre, fun) {
                pre = pre.concat(fun['textSource']);
                return pre;
            }, []);
        }
        return [];
    })
};

var preaddir = Promise.denodeify(require('fs').readdir);
var fetchAllSqls = function () {
    return preaddir(__dirname + xml_path).then(function (files) {
        return Promise.all(files.map(function (file) {
            var fn = (/^(.*)\.xml$/ig).exec(file)[1];
            return fetchSql(fn).then(function (sql) {
                return fetchFormular(fn).then(function (funs) {
                    return {
                        type: 'ORCL',
                        key: fn,
                        sql: sql,
                        functions: funs
                    };
                });
            });
        }));
    });
};
var sync = function () {
    return fetchAllSqls().then(function (data) {
        return pwrite(__dirname + '/orcl_summary.json', JSON.stringify(data));
    })
};
sync().then(console.log, function (err) {
    console.log(err.stack);
});
//fetchFormular('RPT_CARR_COMPLETE_EDI_EVENT').then(console.log, console.log);